<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController extends BackendController
{
    //
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * $type 上传文件夹
     * $width 缩略图宽度
     * $height 缩略图高度
     * $filename 图片重命名
     * $type 判断上传是否为缩略图 (1:缩略图 2:storage上传 null: 都保存)
     * 文件上传根据类型分文件夹
     */
    public function store(Request $request){
        $file = storage_path('app/public/');
        $dir = $request->dir;
        $width = isset($request->width) ? $request->width : '';
        $height = isset($request->height) ? $request->height : '';
        // 判断是否有文件夹
        if(!file_exists($file.$dir)){
            Storage::makeDirectory('/public/'.$dir);
        }
        $image = $request->file('file');
        $filename  = time().rand(10000,99999) . '.' . $image->getClientOriginalExtension();
        if($request->type == 1){
            //  Intervention/image 对图片进行管理
            if(!file_exists($file.$dir.'/'.date('Y-m-d',time()))){
                Storage::makeDirectory('/public/'.$dir.'/'.date('Y-m-d',time()));
            }
            $path = storage_path('app/public').'/'.$dir.'/'.date('Y-m-d',time()).'/'.$filename;
            \Image::make($image->getRealPath())->resize($width,$height)->save($path);
            return response()->json([
                'status' => 200,
                'thumb' => '/storage/'.$dir.'/'.date('Y-m-d',time()).'/'.$filename
            ]);
        }else if($request->type == 2){
            //  laravel 自带上传方法
            $path1 = $image->store($dir.'/'.date('Y-m-d',time()),'public');
            $url = Storage::url($path1);
            return response()->json([
                'status' => 200,
                'photo' => $url,
            ]);
        }else{
            //  laravel 自带上传方法
            $path1 = $image->store($dir.'/'.date('Y-m-d',time()),'public');
            $url = Storage::url($path1);
            //  Intervention/image 对图片进行管理
            $path = storage_path('app/public').'/'.$dir.'/'.date('Y-m-d',time()).'/'.$filename;
            \Image::make($image->getRealPath())->resize($width,$height)->save($path);
            return response()->json([
                'status' => 200,
                'photo' => $url,
                'thumb' => '/storage/'.$dir.'/'.date('Y-m-d').'/'.$filename
            ]);
        }

    }
}
